package com.niodata.dt.fs.http;

import java.io.IOException;
import java.io.InputStream;
import org.apache.hadoop.fs.FSInputStream;

public class HttpFsInputStream extends FSInputStream {

  private static final int buffer_size = 16 * 1024 * 1024;
  private final InputStream inputStream;
  private final int pos = 0;
  private byte[] buffer;
  //new byte[buffer_size + 32];
  private int idx = -1;
  private int length = -1;
  private boolean eof = false;

  public HttpFsInputStream(InputStream inputStream) {
    this.inputStream = inputStream;

  }

  @Override
  public void seek(long l) throws IOException {
    throw new IOException("not supported");
  }

  @Override
  public long getPos() throws IOException {
    return pos;
  }

  @Override
  public boolean seekToNewSource(long l) throws IOException {
    return false;
  }

  @Override
  public int read() throws IOException {
    return inputStream.read();
  }

  private void fillBuffer() throws IOException {
    if ((idx == -1 || length == -1) && !eof) {
      int len = inputStream.read(buffer, 0, buffer_size);
      length = len;
      if (length != -1) {
        idx = 0;
      }
      int b = inputStream.read();
      if (b == -1) {
        eof = true;
      } else {
        buffer[len] = (byte) b;
        length = length + 1;
      }
      return;
    }
    if (idx == length && !eof) {
      int len = inputStream.read(buffer, 0, buffer_size);
      length = len;
      if (length != -1) {
        idx = 0;
      }
      int b = inputStream.read();
      if (b == -1) {
        eof = true;
      } else {
        buffer[len] = (byte) b;
        length = length + 1;
      }
    }
  }
}
